import axios, { AxiosResponse, AxiosError } from 'axios'
import { Message } from 'element-ui'
import store from '../store/index'
import type { Response } from './type'

// Extend Window interface to include BASE_URL
declare global {
  interface Window {
    BASE_URL: string
  }
}

// Create axios instance
const request = axios.create({
  baseURL: window.BASE_URL,
  timeout: 6000000,
})

// Request interceptor
request.interceptors.request.use(
  (config) => {
    if (config.headers && config.headers['Content-Type'] !== 'multipart/form-data') {
      // Handle non-file requests
      if (
        (config.method === 'post' || config.method === 'put') &&
        config.headers['Content-Type'] !== 'application/x-www-form-urlencoded'
      ) {
        config.headers['Content-Type'] = 'application/json'
      }
    } else if (config.headers && config.headers['Content-Type'] === 'multipart/form-data') {
      // Handle file upload timeout
      config.timeout = 2160000
    }
    
    // Add authentication token
    try {
      const user = JSON.parse(window.localStorage.getItem('user') || '{}')
      const token = user && user.token
      if (token && config.headers) {
        config.headers['AUTH-TOKEN'] = config.headers['AUTH-TOKEN'] || token
      }
    } catch (e) {
      console.warn('Failed to parse user from localStorage')
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor with unified error handling
request.interceptors.response.use(
  (response: AxiosResponse): any => {
    // Handle blob responses (file downloads)
    if (Object.prototype.toString.call(response.data) === '[object Blob]') {
      return response
    }
    
    const data = response.data as Response<any>
    
    // Check if response has success field (business logic response)
    if (typeof data === 'object' && data !== null && 'success' in data) {
      // Business logic error handling
      if (!data.success && data.message) {
        // Show error message for failed business operations
        if (Message && typeof Message.error === 'function') {
          Message.error(data.message)
        }
        console.error('Business Logic Error:', data.message)
      }
    }
    
    return data
  },
  (error: AxiosError) => {
    const { response } = error
    if (response) {
      const { status } = response
      
      switch (status) {
        case 400:
          Message.error('参数错误，无法完成请求响应')
          break
        case 401:
          Message.error('登录过期')
          if (store && store.dispatch) {
            store.dispatch('logout')
          }
          break
        case 403:
          Message.error('没有权限访问该资源')
          break
        case 404:
          if (navigator.onLine) {
            Message.error('请求资源未找到!')
          } else {
            Message.error('请检查设备网络是否已连接!')
          }
          break
        case 500:
        case 502:
        case 503:
          if (navigator.onLine) {
            Message.error('服务器错误!')
          } else {
            Message.error('请检查设备网络是否已连接!')
          }
          break
        default:
          Message.error(`请求失败: ${status}`)
      }
    } else {
      // Network error
      if (navigator.onLine) {
        Message.error('网络错误！')
      } else {
        Message.error('请检查设备网络是否已连接!')
      }
    }
    
    console.error('HTTP Error:', error)
    return Promise.reject(error)
  }
)

export default request 